package com.handydata.antifraud.util;

import com.handydata.antifraud.enums.Comment;

import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;

public class ExceptionUtil {
    public static <T> Optional<T> of(SupplierEx<T> supplierEx) {
        Objects.requireNonNull(supplierEx);
        try {
            return Optional.of(supplierEx.get());
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
    public static <T> Optional<T> of(SupplierEx<T> supplierEx, Comment comment) {
        Objects.requireNonNull(supplierEx);
        try {
            return Optional.of(supplierEx.get());
        } catch (Exception ex) {
            throw new RuntimeException(comment.getCode() + "", ex);
        }
    }
    public static <T> Optional<T> of(SupplierEx<T> supplierEx, Consumer<Exception> consumer) {
        Objects.requireNonNull(supplierEx);
        Objects.requireNonNull(consumer);
        try {
            return Optional.of(supplierEx.get());
        } catch (Exception ex) {
            consumer.accept(ex);
            return Optional.empty();
        }
    }

    @FunctionalInterface
    public static interface SupplierEx<T> {

        T get() throws Exception;
    }
}
